//
//  HPCollectMoneyViewController.m
//  HPZZTong
//
//  Created by handpay on 14-3-24.
//  Copyright (c) 2014年 Handpay. All rights reserved.
//

#import "HPCollectMoneyViewController.h"
#import "Utility.h"
#import <MapKit/MapKit.h>
#import "HPPWDScreenViewController.h"
//#import "ZZTCollectMoney.h" // mcm
//#import "POSUIEngine.h" // mcm
#import <HandPaySwiperModule/HandPaySwiperModule.h> // mcm new
#import "RFPOSUIEngine.h" // mcm new
#import "SwipeInfo.h" // mcm new
#import "RFCSNValidatorController.h"

@interface HPCollectMoneyViewController ()<HPSwiperContextDelegate>
{
    BOOL isInputPoint;
    NSString* bankCard;
    IBOutlet UILabel *shopNameLabel;
    IBOutlet UIView *numberbg4View;
}

@property (nonatomic, retain) NSString* amountPrePoint;   //小数点前面
@property (nonatomic, retain) NSString* amountNextPoint;  //小数点后面
//@property (retain,nonatomic) ZZTCollectMoney * collectProcess; // mcm
@property(nonatomic, retain) POSProcess* collectProcess;
@property(nonatomic, retain) RFPOSUIEngine* posProcessMointor;
@end


#define AMOUNT_MAX_LEN          7

@implementation HPCollectMoneyViewController

@synthesize amountPrePoint;
@synthesize amountNextPoint;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        self.showBackButton = NO;
        self.hideBottomBar = NO;
    }
    return self;
}

- (void)changeFrameWithIphone5{
    int top = 0;
    int left = 0;
    int w = 98;
    int h = 64;
    int space = 3;
    
    CGRect frame = numberbg4View.frame;
    frame.size.height += IPHONE5_ADD_HEIGHT;
    numberbg4View.frame = frame;
    
    self.oneButton.frame = CGRectMake(left, top, w, h);
    left += w + space;
    self.twoButton.frame = CGRectMake(left, top, w, h);
    left += w+ space;
    self.threeButton.frame= CGRectMake(left, top, w, h);
    
    left = 0;
    top += h + space;
    self.fourButton.frame = CGRectMake(left, top, w, h);
    left += w + space;
    self.fiveButton.frame = CGRectMake(left, top, w, h);
    left += w + space;
    self.sixButton.frame = CGRectMake(left, top, w, h);
    
    left = 0;
    top += h + space;
    self.sevenButton.frame = CGRectMake(left, top, w, h);
    left += w + space;
    self.eightButton.frame = CGRectMake(left, top, w, h);
    left += w + space;
    self.nineButton.frame = CGRectMake(left, top, w, h);
    
    left = 0;
    top += h + space;
    self.zeroButton.frame = CGRectMake(left, top, w, h);
    left += w + space;
    self.doubleZeroButton.frame = CGRectMake(left, top, w, h);
    left += w + space;
    self.dianButton.frame = CGRectMake(left, top, w, h);
    
    left = 0;
    top += h + space;
    w = w * 2 + space;
    self.okButton.frame = CGRectMake(left, top, w, h);
    left += w + space;
    w = 98;
    self.toBackButton.frame = CGRectMake(left, top, w, h);
    
    [self.oneButton changeBackground:@"numberbuttonbg5.png" highlight:@"numberbuttonbghover5.png"];
    [self.twoButton changeBackground:@"numberbuttonbg5.png" highlight:@"numberbuttonbghover5.png"];
    [self.threeButton changeBackground:@"numberbuttonbg5.png" highlight:@"numberbuttonbghover5.png"];
    [self.fourButton changeBackground:@"numberbuttonbg5.png" highlight:@"numberbuttonbghover5.png"];
    [self.fiveButton changeBackground:@"numberbuttonbg5.png" highlight:@"numberbuttonbghover5.png"];
    [self.sixButton changeBackground:@"numberbuttonbg5.png" highlight:@"numberbuttonbghover5.png"];
    [self.sevenButton changeBackground:@"numberbuttonbg5.png" highlight:@"numberbuttonbghover5.png"];
    [self.eightButton changeBackground:@"numberbuttonbg5.png" highlight:@"numberbuttonbghover5.png"];
    [self.nineButton changeBackground:@"numberbuttonbg5.png" highlight:@"numberbuttonbghover5.png"];
    [self.zeroButton changeBackground:@"numberbuttonbg5.png" highlight:@"numberbuttonbghover5.png"];
    [self.dianButton changeBackground:@"numberbuttonbg5.png" highlight:@"numberbuttonbghover5.png"];
    [self.doubleZeroButton changeBackground:@"numberbuttonbg5.png" highlight:@"numberbuttonbghover5.png"];
    [self.toBackButton changeBackground:@"backspacebuttonbg5.png" highlight:@"backspacebuttonbghover5.png"];
    [self.okButton changeBackground:@"okbuttonbg5.png" highlight:@"okbuttonbghover5.png"];
}
- (void)viewDidDisappear:(BOOL)animated{
    [super viewDidDisappear:animated];
    [self clearData];
}
- (void)viewDidLoad
{
    self.title = @"收款";
    [super viewDidLoad];
    
    isInputPoint = NO;
    
    if (HP_Device_iPhone5) {
        [self changeFrameWithIphone5];
    }
    
    
    self.oneButton.textStr = @"1";
    self.twoButton.textStr = @"2";
    self.threeButton.textStr = @"3";
    self.fourButton.textStr = @"4";
    self.fiveButton.textStr = @"5";
    self.sixButton.textStr = @"6";
    self.sevenButton.textStr = @"7";
    self.eightButton.textStr = @"8";
    self.nineButton.textStr = @"9";
    self.zeroButton.textStr = @"0";
    self.doubleZeroButton.textStr = @"00";
    self.dianButton.textStr = @".";
    [self.okButton changeBackground:@"okbuttonbg.png" highlight:@"okbuttonbghover.png"];
    
    [self.toBackButton changeBackground:@"backspacebuttonbg.png" highlight:@"backspacebuttonbghover.png"];
    [self.toBackButton setCustomImage:@"backspace.png"];

    
    UILongPressGestureRecognizer *longPress = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(backButtonLongPress:)];
//    longPress.minimumPressDuration = 0.8; //定义按的时间
    [self.toBackButton addGestureRecognizer:longPress];
    [longPress release];
    
    self.clearButton.hidden = YES;
    
    self.amountLabel.textColor = kTitleFontColor;
}

- (void)clearData{
    self.amountLabel.text = @"¥0.00";
    isInputPoint = NO;
    self.amountPrePoint = @"";
    self.amountNextPoint = @"";
    self.clearButton.hidden = YES;
}
-(void)backButtonLongPress:(UILongPressGestureRecognizer *)gestureRecognizer{
    if ([gestureRecognizer state] == UIGestureRecognizerStateBegan) {
        LOG(@"长按事件");
        [self clearData];
    }
}
- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
}
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [ZZT_UIENG hideNavigationBar:NO];
    self.tabBarController.tabBar.hidden = NO;
//    [self clearData];
    
    if (ZZT_CLIENG.accountInfo.shopName) {
        shopNameLabel.hidden = NO;
        shopNameLabel.text = ZZT_CLIENG.accountInfo.shopName;
    }else{
        shopNameLabel.hidden = YES;
    }
//    [self hideTabBar:NO];
}
- (void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
    [ZZT_UIENG hideNavigationBar:NO];
    
//    if (![HPUIENG doCheckGPSStatus]) {
//        [HPUIENG showAlert:@"请打开地理位置服务"];
//    }
}

- (void)dealloc {
    [_oneButton release];
    [_twoButton release];
    [_threeButton release];
    [_fourButton release];
    [_fiveButton release];
    [_sixButton release];
    [_sevenButton release];
    [_eightButton release];
    [_nineButton release];
    [_zeroButton release];
    [_doubleZeroButton release];
    [_toBackButton release];
    [_dianButton release];
    [_okButton release];
    [_clearButton release];
    [_amountLabel release];
    self.posProcessMointor = nil;
    self.amountNextPoint = nil;
    self.amountPrePoint = nil;
    bankCard = nil;
    [shopNameLabel release];
    [numberbg4View release];
    [super dealloc];
}
- (void)viewDidUnload {
    [self setOneButton:nil];
    [self setTwoButton:nil];
    [self setThreeButton:nil];
    [self setFourButton:nil];
    [self setFiveButton:nil];
    [self setSixButton:nil];
    [self setSevenButton:nil];
    [self setEightButton:nil];
    [self setNineButton:nil];
    [self setZeroButton:nil];
    [self setDoubleZeroButton:nil];
    [self setToBackButton:nil];
    [self setDianButton:nil];
    [self setOkButton:nil];
    [self setClearButton:nil];
    [self setAmountLabel:nil];
    [shopNameLabel release];
    shopNameLabel = nil;
    [numberbg4View release];
    numberbg4View = nil;
    [super viewDidUnload];
}
- (IBAction)clearButtonClick:(id)sender {
    [self clearData];
}

- (IBAction)numberButtonClick:(id)sender {
    NSString* numberStr = ((HPCustomButton*)sender).textStr;
    NSString* amount = [self.amountLabel.text substringFromIndex:1];
    
    NSString* prePoint = self.amountPrePoint;
    NSString* nextPoint = self.amountNextPoint;
    
    BOOL isPreFlag = [NSString isNilOrEmpty:prePoint];
    BOOL isNextFlag = [NSString isNilOrEmpty:nextPoint];
    
    
    if ([numberStr isEqualToString:@"0"] || [numberStr isEqualToString:@"00"]){
        if (isPreFlag && !isInputPoint) {
            return;
        }
        if (isInputPoint) {
            if ([numberStr isEqualToString:@"00"]) {
                return;
            }else{
                if (!isNextFlag) {
                    return;
                }
            }
        }
    }
    
    if (isInputPoint) {
        if (isNextFlag) {
            
            self.amountNextPoint = numberStr;
            nextPoint = self.amountNextPoint;
            
        }else if(self.amountNextPoint.length < 2){
            self.amountNextPoint = [self.amountNextPoint stringByAppendingString:numberStr];
            nextPoint = self.amountNextPoint;
        }
        
    }else{
        if (isPreFlag) {
            self.amountPrePoint = numberStr;
            prePoint = self.amountPrePoint;
        }else{
            if ((self.amountPrePoint.length >= AMOUNT_MAX_LEN) || ((self.amountPrePoint.length == 6) && (numberStr.length >= 2))) {
                return;
            }
            self.amountPrePoint = [self.amountPrePoint stringByAppendingString:numberStr];
            prePoint = self.amountPrePoint;
        }
    }
    isPreFlag = [NSString isNilOrEmpty:prePoint];
    isNextFlag = [NSString isNilOrEmpty:nextPoint];
    
    if (isPreFlag) {
        prePoint = @"0";
    }
    if (isNextFlag) {
        nextPoint = @"00";
    }
    if (nextPoint.length == 1) {
        nextPoint = [nextPoint stringByAppendingString:@"0"];
    }

    amount = [Utility getFormatMoneyNoSymbol:[prePoint stringByAppendingString:nextPoint]];
    self.amountLabel.text = [@"¥" stringByAppendingString:[Utility formatAmount2:amount]];
    
    if (![self.amountLabel.text isEqualToString:@"¥0.00"]) {
        self.clearButton.hidden = NO;
    }
    
}

- (IBAction)backButtonClick:(id)sender {
    
    NSString* amount = [self.amountLabel.text substringFromIndex:1];
    
    BOOL isPreFlag = [NSString isNilOrEmpty:self.amountPrePoint];
    BOOL isNextFlag = [NSString isNilOrEmpty:self.amountNextPoint];
    
    NSString* prePoint = self.amountPrePoint;
    NSString* nextPoint = self.amountNextPoint;
    
    if ([amount isEqualToString:@"0.00"]) {
        return;
    }
    if (isInputPoint) {
        if (!isNextFlag) {
            nextPoint = [nextPoint substringToIndex:(nextPoint.length - 1)];
            if ([nextPoint isEqualToString:@"0"]) {
                nextPoint = @"";
            }
            
            self.amountNextPoint = nextPoint;
        }else if (!isPreFlag) {
            self.amountPrePoint = prePoint = [prePoint substringToIndex:(prePoint.length - 1)];
        }
        
    }else if (!isPreFlag) {
        self.amountPrePoint = prePoint = [prePoint substringToIndex:(prePoint.length - 1)];
    }
    
    
    isPreFlag = [NSString isNilOrEmpty:prePoint];
    isNextFlag = [NSString isNilOrEmpty:nextPoint];
    
    if (isPreFlag) {
        prePoint = @"0";
    }
    if (isNextFlag) {
        nextPoint = @"00";
    }
    if (nextPoint.length == 1) {
        nextPoint = [nextPoint stringByAppendingString:@"0"];
    }
    
    amount = [Utility getFormatMoneyNoSymbol:[prePoint stringByAppendingString:nextPoint]];
    self.amountLabel.text = [@"¥" stringByAppendingString:[Utility formatAmount2:amount]];
    
    if (![self.amountLabel.text isEqualToString:@"¥0.00"]) {
        self.clearButton.hidden = NO;
        
    }else{
        isInputPoint = NO;
    }

}

- (IBAction)okButtonClick:(id)sender {
    NSString* moneyStr = [self.amountLabel.text substringFromIndex:1];
    
    if ([NSString isNilOrEmpty:moneyStr] || [moneyStr isEqualToString:@"0.00"]){
        [HPUIENG showAlert:@"请输入收款金额"];
        return;
    }
    NSString* alertStr = @"收款金额不能少于10元";
    if ([NSString isNilOrEmpty:self.amountPrePoint]) {
        [HPUIENG showAlert:alertStr];
        return;
    }else{
        if (self.amountPrePoint.intValue < 10) {
            [HPUIENG showAlert:alertStr];
            return;
        }
    }
    ZZTongClientEngine* zzt = ZZT_CLIENG;
    
    if (![zzt checkAccountStatus:FunctionTypeCollectMoney]) {
        return;
    }
    
//    _collectProcess = [[ZZTCollectMoney alloc] init]; // mcm
    
    
    // mcm
    //    [SWIPERENG selectSwiperAndGetCsn:^(HPSwiperResult *swiperResult) {
    //        [self beginCollectMoney];
    //        return;
    //    } isShow:NO];
    
    // mcm new
    if ([HPSwiperContext sharedInstance].connectedDeviceCSN.length)
    {
        [self initPOSProcess];
        [self beginCollectMoney];
    }
    else
    {
        [[HPSwiperContext sharedInstance] addDelegate:self];
        [HPUIENG showScreen:SCR_SWIPER_SELECT];
    }
}

-(void)initPOSProcess
{
    self.collectProcess = [[HPSwiperContext sharedInstance] processorWithBindingInfo:nil businessType:HPPOSBusinessTypeCollectMonety]; // mcm new
    self.posProcessMointor = [[RFPOSUIEngine alloc] initWithPOSProcess:self.collectProcess];
    self.collectProcess.plainAmount = [self moneyStr];
//    if (!self.collectProcess)
//    {
//
//    }
}

- (void)beginCollectMoney
{
    [self.collectProcess beginWithDelegate:self]; // mcm
}

- (void)selectApplication:(id)process result:(HPSwiperResult *)result{
    NSArray* array = (NSArray*)result.value;
    
    NSMutableArray* mutArray = [NSMutableArray array];
    
    for (int i = 0; i<array.count; i++) {
        NSString* strData = [array objectAtIndex:i];
        if (![NSString isNilOrEmpty:strData]) {
            NSString* strTemp = [strData uppercaseString];
            NSString* strName = nil;
            
            NSRange range = [strTemp rangeOfString:@"CREDIT"];
            if (range.length != 0) {
                strName = @"信用卡";
            }
            range = [strTemp rangeOfString:@"DEBIT"];
            if (range.length != 0) {
                strName = @"借记卡";
            }
            
            if (![NSString isNilOrEmpty:strName]) {
                [mutArray addObject:@[strName,strData,[NSNumber numberWithInt:i]]];
            }
        }
    }
    
//    [POSUIENG processSelectApp:mutArray]; // mcm
    [self.posProcessMointor processSelectApp:mutArray]; // mcm new
}
- (void)process:(POSProcess *)process finishedWithResult:(HPSwiperResult *)result
{
    if (!result.isSuccess)
    {
//        [POSUIEngine processFailed:process result:result]; // mcm
        [RFPOSUIEngine processFailed:self.collectProcess result:result]; // mcm new
    }
    else
    {
        [self doTransfer];
    }
}

- (NSString *)moneyStr
{
    NSString* moneyStr = @"";
    if (![NSString isNilOrEmpty:self.amountPrePoint]) {
        moneyStr = self.amountPrePoint;
    }
    if (![NSString isNilOrEmpty:self.amountNextPoint]) {
        moneyStr = [moneyStr stringByAppendingString:self.amountNextPoint];
        if (self.amountNextPoint.length == 1) {
            moneyStr = [moneyStr stringByAppendingString:@"0"];
        }
    }else{
        moneyStr = [moneyStr stringByAppendingString:@"00"];
    }
    return [Utility leftPadding:moneyStr withTotalCount:10 withChar:@"0"];
}

- (void)doTransfer{
    
    [ZZT_UIENG showNetWaiting];
    
    ZZTongClientEngine * zztEngine = [ZZTongClientEngine sharedInstance];
    NSString* csn = [HPSwiperContext sharedInstance].connectedDeviceCSN;
    RFCSNValidatorController* validator = [RFCSNValidatorController sharedInstance];
    
    NSMutableDictionary* params = [NSMutableDictionary dictionary];

    if (![NSString isNilOrEmpty:self.collectProcess.encAccount]) {
        [params setObject:self.collectProcess.encAccount forKey:@"cardNo"];
    }else if(![NSString isNilOrEmpty:self.collectProcess.swipeInfo.encAccount]){
        [params setObject:self.collectProcess.swipeInfo.encAccount forKey:@"cardNo"];
    }
    if (![NSString isNilOrEmpty:self.collectProcess.encPin]) {
        [params setObject:self.collectProcess.encPin forKey:@"pin"];
    }else if(![NSString isNilOrEmpty:self.collectProcess.swipeInfo.encPin]){
        [params setObject:self.collectProcess.swipeInfo.encPin forKey:@"pin"];
    }
    [params setObject:_collectProcess.encAmount forKey:@"amount"];
    [params setObject:_collectProcess.factor forKey:@"factor"];
    [params setObject:DES_ENC(csn) forKey:KEY_CSN];
    [params setObject:DES_ENC(ZZT_CLIENG.accountInfo.account) forKey:KEY_ACCOUNT];
    
//    [params setObject:[CSNValidator getLocation] forKey:KEY_LOCATION]; // mcm
//    [params setObject:[CSNValidator getAddress] forKey:KEY_ADDRESS]; // mcm
    [params setObject:validator.location forKey:KEY_LOCATION]; // mcm new
    [params setObject:validator.address forKey:KEY_ADDRESS]; // mcm new
    
    [params setObject:[zztEngine getChannel] forKey:KEY_CHANNEL];
    if (_collectProcess.icMode)
    {
        if (_collectProcess.swipeInfo.icNumber.length > 0)
        {
            [params setObject:_collectProcess.swipeInfo.icNumber forKey:@"ICNumber"];
        }
        [params setObject:_collectProcess.swipeInfo.dcData forKey:@"DCData"];
        [params setObject:_collectProcess.encMac forKey:@"mac"];
    }
    if (![NSString isNilOrEmpty:_collectProcess.swipeInfo.encTrack2]) {
        [params setObject:_collectProcess.swipeInfo.encTrack2 forKey:@"track2"];
    }
    if (![NSString isNilOrEmpty:_collectProcess.swipeInfo.dynamicKey]) {
        [params setObject:_collectProcess.swipeInfo.dynamicKey forKey:@"dynamicKeyData"];
    }

    [zztEngine.netEngine sendRequest:NET_ACTION_ACCOUNT_TRANSFER withParams:params withDelegate:self withAlertFlag:NO];
}

- (IBAction)dianButtonClick:(id)sender {
    isInputPoint = YES;
}
- (void)treatTransferSuccess:(NSDictionary*)respData{
    NSString* status = [respData objectForKey:@"status"];
    if ([status isEqualToString:@"1"]) { //成功
        [HPUIENG showScreen:SCR_SIGN_TRANSACTION params:respData];
    } else {
        NSString* transTime = [respData objectForKey:@"transTime"];
        NSString* transSN = [respData objectForKey:@"transSN"];
        NSString* transStatus = [respData objectForKey:@"transStatus"];
        
        NSString* cardNoOut = [Utility encryptCardID:[respData objectForKey:@"cardNoOut"]];
        NSString* amount = [Utility getFormatMoneyAndSymbol:[respData objectForKey:KEY_AMOUNT]];
        
        NSString* tranMediaType = [respData objectForKey:@"tranMediaType"];
        if (![NSString isNilOrEmpty:tranMediaType]) {
            cardNoOut = [[cardNoOut stringByAppendingString:@" /"]stringByAppendingString:tranMediaType];
        }
        
        NSArray*  aboveData = @[@[@"交易类型", @"消费/SALE"],
                                @[@"交易流水号",transSN],
                                @[@"交易时间", [Utility getFormatDate:transTime]],
                                @[@"消费卡号", cardNoOut],
                                @[@"消费金额", amount]];
        
        NSArray* belowData = nil;
        if ([status isEqualToString:@"2"]) {
            belowData = @[@[@"", transStatus, @"3"]];
        }else{
            belowData = @[@[@"失败原因", transStatus, @"3"]];
        }
        
        
         NSDictionary* dic = @{kTransType: transTypeTransfer,
                               kAboveData: aboveData,
                               kBelowData: belowData,
                               kBusinissType:transResult,
                               @"status": status};
        
        [HPUIENG showScreen:SCR_TRANSACTION_FAIL params:dic];
    }
    
}

#pragma net callback

-(void)responseCallBackSuccess:(NSString *)action withData:(NSDictionary *)respData{
    [HPUIENG removeWaiting];
    if ([action isEqualToString:NET_ACTION_ACCOUNT_TRANSFER]) {
        [self treatTransferSuccess:respData];
    }
}

- (void)responseCallBackFailed:(NSString *)action withErrCode:(NSString *)errCode withErrMsg:(NSString *)msg{
    if([action isEqualToString:NET_ACTION_ACCOUNT_TRANSFER]){
        [HPUIENG popScreen];
        [HPUIENG showAlert:msg];
    }
}

#pragma HPSwiperContextDelegate

-(void)choiseYourDevice:(NSArray*)devices{}

-(void)swiperCsnDidChange:(NSString*)didChangeCsn
{
    [[HPSwiperContext sharedInstance] removeDelegate:self];
    [HPUIENG removeWaiting];
    if (didChangeCsn.length)
    {
        [[RFCSNValidatorController sharedInstance] validateCSNComplete:^(BOOL succ, NSString *errInfo) {
            if (!succ)
            {
                [[HPUIEngine getInstance] showAlert:errInfo];
            }
            else
            {
                [self initPOSProcess];
                [self beginCollectMoney];
            }
        } autoTip:NO];
    }
}
@end
